package net.narusas.aceauction.push;

import java.util.ArrayList;
import java.util.List;

import net.narusas.aceauction.push.model.Device;

import javapns.Push;
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class APSNPushService implements PushService {
	String certificationPath;
	String password;
	boolean distributeMode;

	@Override
	public void pushText(Device device, String message) {
		if (device.isIOSDevice() == false || device.getPushToken() == null) {
			return;
		}
		pushText(message, new String[] { device.getPushToken() });
	}

	void pushText(String message, String[] tokens) {
		log.info("아이폰에 메시지를 전송합니다.PUSH ID: {}", tokens);
		try {
			Push.alert(message,//
					certificationPath,//
					password, //
					distributeMode,//
					tokens);
		} catch (CommunicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeystoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void pushText(List<Device> devices, String message) {
		List<String> tokensCollection = new ArrayList<String>();
		for (Device device : devices) {
			if (device.isIOSDevice() && device.getPushToken() != null) {
				tokensCollection.add(device.getPushToken());
			}
		}
		pushText(message, tokensCollection.toArray(new String[tokensCollection.size()]));

	}
	
	@Override
	public void pushBadge(Device device, int badgeCount) {
		if (device.isIOSDevice() == false || device.getPushToken() == null) {
			return;
		}
		pushBadge(badgeCount, new String[] { device.getPushToken() });
	}

	private void pushBadge(int badgeCount, String[] tokens) {
		// TODO Auto-generated method stub
		log.info("아이폰에 메시지를 전송합니다.PUSH ID: {}", tokens);
		try {
			Push.badge(badgeCount,//
					certificationPath,//
					password, //
					distributeMode,//
					tokens);
		} catch (CommunicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeystoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
